package com.space9.search.service.impl;

import java.util.List;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.space9.common.pojo.Space9Result;
import com.space9.search.mapper.ItemMapper;
import com.space9.search.pojo.Item;
import com.space9.search.service.ItemService;

@Service
public class ItemServiceImpl implements ItemService {

	@Autowired
	private ItemMapper itemMapper;
	
	@Autowired
    private RestHighLevelClient rhlClient;
	
	@Override
	public Space9Result importAllItems() {
		try {
			//查询商品列表
			List<Item> list = itemMapper.getItemList();
			//把商品信息写入索引库
			BulkRequest bulkRequest = new BulkRequest();
			for (Item item : list) {
				IndexRequest indexRequest = new IndexRequest("mydb", "mytable", item.getId());
				indexRequest.source(XContentType.JSON,
							"id", item.getId(),
							"item_title", item.getTitle(),
							"item_sell_point", item.getSell_point(),
							"item_price", item.getPrice(),
							"item_image", item.getImage(),
							"item_category_name", item.getCategory_name(),
							"item_desc", item.getItem_des());
				bulkRequest.add(indexRequest);
			}
			//提交修改
			rhlClient.bulk(bulkRequest);
		} catch (Exception e) {
			e.printStackTrace();
			return Space9Result.build(500, e.getMessage());
		}
		return Space9Result.ok();
	}

}
